<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      class="uniform-form"
    >
      <el-form-item label="报告名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入报告名称"
        />
      </el-form-item>

      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="formData.startTime"
          type="datetime"
          placeholder="选择开始时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          required
        />
      </el-form-item>

      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="formData.endTime"
          type="datetime"
          placeholder="选择结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          required
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { useMessage } from '@/hooks/web/useMessage'
import { PresentationApi, PresentationVO } from '@/api/member/presentation'

/** 报告 表单 */
defineOptions({ name: 'PresentationForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中状态
const formType = ref<string>('') // 表单的类型：create - 新增；update - 修改
const formData = ref<Partial<PresentationVO>>({
  id: undefined,
  name: undefined,
  remark: undefined,
  startTime: undefined,
  endTime: undefined
})

const formRules = reactive({
  name: [
    { required: true, message: '报告名称不能为空', trigger: 'blur' },
    { max: 100, message: '报告名称不能超过100个字符', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '开始时间不能为空', trigger: 'change' },
    {
      validator: (_rule: any, value: string, callback: any) => {
        if (value && formData.value.endTime && new Date(value) > new Date(formData.value.endTime)) {
          callback(new Error('开始时间不能晚于结束时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  endTime: [
    { required: true, message: '结束时间不能为空', trigger: 'change' },
    {
      validator: (_rule: any, value: string, callback: any) => {
        if (value && formData.value.startTime && new Date(value) < new Date(formData.value.startTime)) {
          callback(new Error('结束时间不能早于开始时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
})

const formRef = ref<any>() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 修改时，加载数据
  if (id) {
    formLoading.value = true
    try {
      const detail = await PresentationApi.getPresentation(id)
      formData.value = { ...detail }
    } catch (error) {
      console.error('加载报告详情失败:', error)
      message.error(t('common.loadFailed'))
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  if (!formRef.value) return

  try {
    // 校验表单
    await formRef.value.validate()

    // 提交请求
    formLoading.value = true
    const data = formData.value as PresentationVO

    if (formType.value === 'create') {
      await PresentationApi.createPresentation(data)
      message.success(t('common.createSuccess'))
    } else if (formType.value === 'update') {
      await PresentationApi.updatePresentation(data)
      message.success(t('common.updateSuccess'))
    }

    dialogVisible.value = false
    emit('success') // 通知父组件刷新数据
  } catch (error: any) {
    // 表单验证失败或请求异常
    if (error.name !== 'ValidationError') {
      console.error('提交表单失败:', error)
      message.error(t('common.operationFailed') + (error.message || ''))
    }
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    remark: undefined,
    startTime: undefined,
    endTime: undefined
  }
  formRef.value?.resetFields()
}
</script>

<style scoped>
/* 表单容器样式 */
.uniform-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 0 16px;
}

/* 统一所有表单控件宽度 */
:deep(.el-form-item) {
  margin-bottom: 16px;
}

/* 输入框宽度控制 */
:deep(.el-form-item .el-input) {
  width: 100% !important;
}

/* 日期选择器宽度控制 */
:deep(.el-form-item .el-date-editor) {
  width: 100% !important;
}

/* 确保禁用状态下也保持一致宽度 */
:deep(.el-input.is-disabled .el-input__wrapper),
:deep(.el-date-editor.is-disabled) {
  width: 100% !important;
}
</style>
